<template>
  <section>
    <!-- 工具条：高级查询和新增 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
            <!-- 上下架 -->
        <el-form-item>
          <el-button type="success" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 列表 -->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="40"></el-table-column>
      <!--<el-table-column prop="id" label="宠物ID" width="60" sortable></el-table-column>-->
      <el-table-column prop="name" label="宠物名称" width="120" sortable></el-table-column>
      <el-table-column prop="petType.name" label="宠物类型" width="120" sortable></el-table-column>
      <el-table-column prop="costprice" label="成本" width="80" sortable></el-table-column>
      <el-table-column prop="saleprice" label="售价" width="80" sortable></el-table-column>
      <!--<el-table-column prop="resources" label="图片" width="120" sortable></el-table-column>-->
      <!--&lt;!&ndash; 图片展示 &ndash;&gt;
      <el-table-column prop="resources" label="图片" width="100" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources" width="80px">
        </template>
      </el-table-column>-->
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else-if="scope.row.state==0">下架</span>
        </template>
      </el-table-column>
      <!--<el-table-column prop="offsaletime" label="下架时间" width="100" sortable></el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable></el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100" sortable></el-table-column>-->
      <el-table-column prop="shop.name" label="所属店铺" width="120" sortable></el-table-column>
      <el-table-column prop="user.username" label="领养用户" width="100" sortable></el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="120" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.searchMasterMsgId">来自寻主</span>
          <span style="color: red" v-else>店铺伺养</span>
        </template>
      </el-table-column>
      <!-- 编辑、删除按纽 -->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除、分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :total="totals"
          :current-page="currentPage"
          :page-size="pageSize"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="50%">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <!-- 无限级树（级联选择器） - 宠物类型树 -->
        <el-form-item label="宠物类型" prop="typeId">
          <el-cascader v-model="saveForm.typeId"
                       :options="petTypeTree"
                       :props="{ checkStrictly: true, label:'name', value:'id' }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="成本" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <!-- 图片上传 -->
        <el-form-item prop="resources" label="图片">
          <!--
              :on-preview="handlePreview" - 点击图片名时触发此函数 - 可以在这里做放大功能，这里不做
              :on-remove="handleRemove" - 点击删除时触发
              :on-success="handleSuccess" - 上传成功之后触发
              :file-list="fileList" - 文件列表
              action="http://localhost:8080/fastDfs/" - 文件上传接口地址
          -->
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--<el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <!-- 店铺下拉框 -->
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择" clearable>
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id" >
              <span style="float: left">{{ item.name }}</span>
              <!--<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>-->
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 领养用户下拉框 -->
        <!--<el-form-item label="领养用户">
          <el-select v-model="saveForm.userId" placeholder="请选择" clearable>
            <el-option
                v-for="item in users"
                :label="item.username"
                :value="item.id" >
              <span style="float: left">{{ item.username }}</span>
              &lt;!&ndash;<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>&ndash;&gt;
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="寻主信息ID" prop="searchMasterMsgId">
          <el-input v-model="saveForm.searchMasterMsgId" auto-complete="off"></el-input>
        </el-form-item>-->

        <!--<el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail"></quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail"></quill-editor>
        </el-form-item>
-->
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption"></quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption"></quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
// 引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor";  // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      // 富文本集成Fastdfs
      quillOption: quillConfig,
      // 列表数据
      pets: [],
      // 忙等框
      listLoading: false,
      // 列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",

      // 1.分页查询的3个参数
      totals: 0,
      currentPage: 1,
      pageSize: 5,

      // 2.高级查询（关键字查询）
      keyword:'',

      // 4.批量删除
      sels: [],  // 列表选中列

      // 5.新增/编辑
      title: '',
      saveFormVisible: false,  // 保存对话框是否显示
      saveLoading: false,  // 保存的忙等框，在提交按纽上
      saveFormRules: {  //保存表单验证规则
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        typeId: [
          {required: true, message: '请选择宠物类型', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ]
      },

      // 新增界面数据：字符串用''，包装类用null
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0,  // 默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail: {  // 与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },

      // 下拉框数据 - 宠物、店铺
      shops: [],
      users: [],

      // 上级宠物处理-无限极树-宠物树
      petTypeTree: [],

      // 显示图片的数据集合
      fileList: []

    }
  },


  methods: {
    // 1.获取列表
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;  // 显示忙等框
      this.$http.post("/pet", para).then(res => {
        this.totals = res.data.totals;  // 赋值总条数
        this.pets = res.data.data;  // 赋值分页数据
        this.listLoading = false;   // 隐藏忙等框
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试！")
      });
    },

    // 2.点击实现 分页查询方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    // 3.高级查询
    keywordQuery() {
      this.currentPage = 1;  // debug
      this.getPets();
    },

    // 4.删除
    handleDel: function (index, row) {
      // 确认框
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        // 点确认后
        this.listLoading = true;
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");
            // 处理当前页问题
            if (this.currentPage != 1
                && (this.totals - 1) % this.pageSize == 0
                && this.currentPage == Math.ceil(this.totals / this.pageSize)) {
              this.currentPage = this.currentPage - 1;
            };
            this.getPets();
          } else {
            this.$message.error("系统繁忙，请稍后重试【500】");
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试！【400,404】")
        });
      }).catch(() => {  // 点取消后

      })
    },

    // 勾选状态改变时触发
    selsChange: function (sels) {
      console.log(sels);
      this.sels = sels;
    },
    // 5.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
            this.listLoading = true;
            this.$http.patch("/pet", ids).then(res => {
              this.listLoading = false;
              if (res.data.success) {
                this.$message.success("批量删除成功");
                this.currentPage = 1; // 回到第一页
                this.getPets();
              } else {
                this.$message.error("系统繁忙，请稍后重试！【500】");
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试！【400,404】")
            });
          }
      ).catch(() => {

      });
    },

    // 6.点击新增弹出对话框
    handleAdd: function () {
      this.addFormVisible = true;
      // 重置表单
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0,  // 默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail: {  // 与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };
      this.title = "新增";
      this.getShops();
      //this.getUsers();
      this.getPetTypeTree();
      this.fileList = [];  // 清空fileList的数据
      this.saveFormVisible = true;  // 显示对话框
    },

    // 点击编辑弹出对话框
    handleEdit: function (index, row) {
      this.saveForm = Object.assign({}, row);  // 回显数据（row含id），不直接 = row是防止双绑导致以前的数据随着变化
      this.title = "编辑";
      this.getShops();
      //this.getUsers();
      this.getPetTypeTree();

      // 处理fileList - 点击修改能够回显图片
      this.fileList = [];  // 之前做了绑定，fileList有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i < arr.length;i++){
          var item = arr[i];  // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
      // 显示详情：两种方案：1.直接在分页查询时就把详情一并查询出来(采用)  2.点击编辑按钮弹出模态框的时候单独查询

      this.saveFormVisible = true;  // 显示对话框
    },

    // 点击保存按纽提交数据
    saveSubmit: function () {
      // 表单验证
      this.$refs.saveForm.validate((valid) => {
        if (valid) { // 验证通过
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            /*// 部门名处理
             para.department_id = para.department;
             para.department = null;
             console.log(para)*/

            // 提交数据时，上级宠物ID的数据格式处理：[3,8]-->{id:8}，级联数组[]转为Long
            let arr = para.typeId;
            if (arr){
              // 点击清理时，为null
              if (arr.length == 0){
                para.typeId = null;
              }
              // [1,13]
              if (arr.length > 0){
                para.typeId = arr[arr.length - 1];
              }
            }

            this.$http.put("/pet", para).then(res => {
              this.saveLoading = false;
              this.saveFormVisible = false;
              if (res.data.success) {
                this.$message.success("操作成功");
                this.getPets();
              } else {
                this.$message.error("系统繁忙，请稍后重试！【500】");
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试！【400,404】");
            });

          });
        }
      });
    },

    // 获取下拉框数据 - departments
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      });
    },
    getUsers() {
      this.$http.get("/user").then(res => {
        this.users = res.data;
      });
    },

    // 获取无限级树 - 宠物类型树
    getPetTypeTree(){
      this.$http.get("petType/petTypeTree").then(res => {
        this.petTypeTree = res.data;
      });
    },

    // 图片预览
    /*handlePreview(file) {
      console.log(file);
    },*/

    // 点击上传成功之后对resources【操作数据库】和fileList【前台显示】做处理
    handleSuccess(response, file, fileList){
      //console.log(response);  //Object { success: true, msg: "操作成功", resultObj: "/group1/M00/00/0F/oYYBAGJ6JV2ANENZAAhNlgqHjro238.gif" }
      //console.log(file);
      //console.log(fileList);

      // 1.处理resources - 添加到数据库
      if (this.saveForm.resources){  // 有值返回true
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      }else {
        this.saveForm.resources = response.resultObj;
      }
      // 2.处理fileList - 前端显示图片
      this.fileList = [];  // 先清空，再添加新的数据
      if (this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for (var i = 0;i < arr.length;i++){
          var item = arr[i];  // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url": "http://123.207.27.208" + item});
        }
      }
    },

    // 调用删除接口删除图片
    // 点击删除图片之后对resources【操作数据库】和fileList【前台显示】做处理
    handleRemove(file, fileList) {
      // 1.调用删除接口删除图片
      //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
      //console.log(file);
      //http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path="+path).then(res => {
        if(res.data.success){
          this.$message.success("删除成功")
        }else{
          this.$message.error("删除失败")
        }
      });

      // 2.处理resources
      // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i < arr.length;i++){
          var item = arr[i];
          if(path == item){  // 找到了删除的图片
            arr.splice(i,1);  // 删除指定的图片
          }
        }
        this.saveForm.resources = arr.join(",");
      }

      // 3.处理fileList - 前端显示图片
      this.fileList = [];  // 之前做了绑定，fileList有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i < arr.length;i++){
          var item = arr[i];  // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }

    },

    // 宠物上架
    onsale(){
      if(this.sels.length==0){  // 没有选
        this.$message.warning("请选择需上架的宠物！");
        return;
      }
      this.$confirm('确认上架选中的宠物吗？', '提示', {type: 'warning'}).then(() => {  // 点击确定
        var ids = this.sels.map(item => item.id);  // [1,2,3]
        this.$http.post("/pet/onsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("上架成功");
            this.getPets();
          }else{
            this.$message.warning("系统繁忙【500】");
          }
        }).catch(res=>{
          this.$message.warning("系统繁忙【400,404】");
        })
      }).catch(() => {
      });
    },

    // 宠物下架
    offsale(){
      if(this.sels.length==0){  // 没有选
        this.$message.warning("请选择需下架的宠物！");
        return;
      }
      this.$confirm('确认下架选中的宠物吗？', '提示', {type: 'warning'}).then(() => { //点击确定
        var ids = this.sels.map(item => item.id);  // [1,2,3]
        this.$http.post("/pet/offsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("下架成功");
            this.getPets();
          }else{
            this.$message.warning("系统繁忙【500】");
          }
        }).catch(res=>{
          this.$message.warning("系统繁忙【400,404】");
        })
      }).catch(() => {
      });
    }



  },

  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>